package com.mike.bdb.ui.provider.table;

import java.lang.reflect.Method;

import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mike.bdb.util.DataCurrent;
import com.mike.bdb.util.ReflectUtil;

public class MikeTableViewerSorter extends ViewerSorter {

	private static final Logger LOG = LoggerFactory.getLogger(MikeTableViewerSorter.class);
	
	/**正向*/
	private static final int ASCENDING = 0;
	/**反向*/
    private static final int DESCENDING = 1;
    
    private int direction;
    
	private volatile String columnName = "";
	
	public void doSort(String attributName) {
		if (LOG.isDebugEnabled()) {
			LOG.debug("设置新的排列方式" + attributName);
		}
		if(columnName.endsWith(attributName)) {
			//切换
			direction = 1 - direction;
		} else {
			this.columnName = attributName;
			//正向排序
			direction = ASCENDING;
		}
	}
	
	@Override
	public int compare(Viewer viewer, Object resource, Object target) {
		int rc = 0;
		String curStoreClazz = DataCurrent.getInstance().curStoreClazz;
		Class<Object> classBy = ReflectUtil.getClassBy(curStoreClazz);
		Method method = ReflectUtil.getMethod(classBy, columnName);
		try {
			Object rv = method.invoke(resource, null);
			Object tv = method.invoke(target, null);
			int rl = rv.toString().length();
			int tl = tv.toString().length();
			rc = rl - tl;
			if (rc == 0) {
				rc = getCharValue(rv, tv, 0);
			}
		} catch (Exception e) {
			//ignore
		}
		
		// If descending order, flip the direction
	    if (direction == DESCENDING) rc = -rc;
	    return rc;
	}

	private int getCharValue(Object rv, Object tv, int index) {
		if(index >= rv.toString().length()) return 0;
		if(index >= tv.toString().length()) return 0;
		char r_char = rv.toString().charAt(index);
		char t_char = tv.toString().charAt(index);
		int rc = r_char - t_char;
		return rc == 0 ? getCharValue(rv, tv, ++index) : rc;
	}
	
}
